package com.liang.auth.application.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.base.Preconditions;
import com.liang.auth.application.convert.AuthRoleDTOConverter;
import com.liang.auth.application.dto.AuthRoleDTO;
import com.liang.auth.api.entity.Result;
import com.liang.auth.domain.bo.AuthRoleBO;
import com.liang.auth.domain.service.AuthRoleDomainService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
public class RoleController {

    private final AuthRoleDomainService authRoleDomainService;

    /**
     * 新增角色
     */
    @PostMapping("/save")
    public Result<Void> save(@RequestBody AuthRoleDTO authRoleDTO) {
        log.info("RoleController.save.dto：{}", JSONUtil.toJsonStr(authRoleDTO));
        try {
            Preconditions.checkArgument(!StrUtil.isBlank(authRoleDTO.getRoleName()), "角色名称不能为空");
            Preconditions.checkArgument(!StrUtil.isBlank(authRoleDTO.getRoleKey()), "角色Key不能为空");
            AuthRoleBO authRoleBO = AuthRoleDTOConverter.INSTANCE.convertDTO2BO(authRoleDTO);
            authRoleDomainService.save(authRoleBO);
            return Result.ok("新增角色成功");
        } catch (Exception e) {
            log.error("RoleController.save.error：{}", e.getMessage(), e);
            return Result.fail("新增角色失败");
        }
    }

    /**
     * 修改角色
     */
    @PostMapping("/update")
    public Result<Void> update(@RequestBody AuthRoleDTO authRoleDTO) {
        log.info("RoleController.update.dto：{}", JSONUtil.toJsonStr(authRoleDTO));
        try {
            Preconditions.checkNotNull(authRoleDTO.getId(), "角色ID不能为空");
            AuthRoleBO authRoleBO = AuthRoleDTOConverter.INSTANCE.convertDTO2BO(authRoleDTO);
            authRoleDomainService.update(authRoleBO);
            return Result.ok("修改角色成功");
        } catch (Exception e) {
            log.error("RoleController.update.error：{}", e.getMessage(), e);
            return Result.fail("修改角色失败");
        }
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/delete")
    public Result<Void> delete(@RequestBody AuthRoleDTO authRoleDTO) {
        log.info("RoleController.delete.authRoleDTO：{}", JSONUtil.toJsonStr(authRoleDTO));
        try {
            Long id = authRoleDTO.getId();
            Preconditions.checkNotNull(id, "角色ID不能为空");
            authRoleDomainService.delete(id);
            return Result.ok("删除角色成功");
        } catch (Exception e) {
            log.error("RoleController.delete.error：{}", e.getMessage(), e);
            return Result.fail("删除角色失败");
        }
    }
}
